<?php
    @header("Content-Type:text/html;charset=utf-8");

    @include_once("conn.php"); 
    @include_once("common.php");


    if(!(isset($_GET["type"]) && isset($_GET["orderCol"]) && isset($_GET["orderType"])&& isset($_GET["pageIndex"])&& isset($_GET["showNum"]))){
        paramsErr();
    }

    $type = $_GET["type"];
    $orderCol = $_GET["orderCol"];  // 排序的条件 (id sales nowprice)
    $orderType = $_GET["orderType"]; //排序的方式 (asc desc)
    $pageIndex = $_GET["pageIndex"];
    $showNum = $_GET["showNum"];
    $skipNum = ($pageIndex-1)*$showNum;
    $sql = "select count(*) as c from `products` where pname  like '%$type%'";
    $obj = array();
    $resultAll = mysqli_query($conn,$sql);
    if($resultAll){
        $item = mysqli_fetch_assoc($resultAll);
        $count = $item["c"];
        $maxPage = ceil($count / $showNum);

        //临界值限制
        if($pageIndex > $maxPage){
            $pageIndex = $maxPage;
        }
        if ($pageIndex < 1){
            $pageIndex = 1;
        }
        $skipNum = ($pageIndex-1)*$showNum;
         $sql = "select  * from `products` where pname  like '%$type%' order by $orderCol $orderType limit $skipNum,$showNum";
        $result = mysqli_query($conn,$sql);

    
    if($result){ // 判断查询的结果

        $list = array();
        while($item = mysqli_fetch_assoc($result)){  // 循环解析数据  有数据 => 继续解析,没有数据=> false => 跳出循环
            // 数据的预处理
            array_push($list,$item);
        }

        $obj["status"] = true;
        $obj["msg"] = "success";
        $obj["count"] = $count*1;  
        $obj["maxPage"] = $maxPage;
        $obj["currentIndex"] = $pageIndex;
        $obj["list"] = $list;
    }else{
        $obj["status"] = false;
        $obj["msg"] = "sql语句有误";
        $obj["sql"] = $sql;
    }
    }else{
        $obj["status"] = false;
        $obj["msg"] = "sql语句有误";
        $obj["sql"] = $sql;
    }

   
    echo json_encode($obj);
?>